package com.quanyan.comment.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.*;
import com.google.protobuf.Api;
import com.quanyan.api.APIResponse;
import com.quanyan.comment.mapper.CommentDetailScoreSumMapper;
import com.quanyan.comment.mapper.TbCommentDetailMapper;
import com.quanyan.comment.mapper.TbCommentDetailScoreMapper;
import com.quanyan.comment.mapper.TbCommentMapper;
import com.quanyan.comment.model.po.*;
import com.quanyan.comment.reqeust.ReqCommentQuery;
import com.quanyan.comment.response.RespCommentDetail;
import com.quanyan.comment.response.RespCommentDetailScore;
import com.quanyan.comment.service.CommentDetailService;
import com.quanyan.common.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/16.
 */
@Service
public class CommentDetailServiceImpl implements CommentDetailService {

    private static final Logger logger = LoggerFactory.getLogger(CommentDetailServiceImpl.class);

    @Autowired
    private TbCommentDetailMapper tbCommentDetailMapper;

    @Autowired
    private TbCommentDetailScoreMapper tbCommentDetailScoreMapper;

    @Autowired
    private CommentDetailScoreSumMapper commentDetailScoreSumMapper;


    @Autowired
    private TbCommentMapper tbCommentMapper;


    @Override
    public APIResponse<List<RespCommentDetail>> getCommentDetailPro(String businessCode,Integer businessId) {
        if(!StringUtils.isNotBlank(businessCode))
            return APIResponse.returnFail("businessCode 不能为空");
        TbCommentDetailExample example = new TbCommentDetailExample();
        TbCommentDetailExample.Criteria criteria = example.createCriteria();
        criteria.andBusinessCodeEqualTo(businessCode);
        if (businessId != null )
            criteria.andBusinessIdEqualTo(businessId);
        try {
            List<TbCommentDetail> lst = tbCommentDetailMapper.selectByExample(example);
            List<RespCommentDetail> respCommentDetails = null;
            if(lst != null && lst.size()>0){
                respCommentDetails = new ArrayList<RespCommentDetail>();
                for (TbCommentDetail c : lst){
                    RespCommentDetail r = new RespCommentDetail();
                    r.setCommentDetailId(c.getId());
                    r.setCommentDetailName(c.getCommentDetailName());
                    r.setCommentDetailCode(c.getBusinessCode());
                    respCommentDetails.add(r);
                }
                logger.info("end 获取业务：{}，评价的项目:{}", businessCode,respCommentDetails.toString());
            }
            return APIResponse.returnSuccess(respCommentDetails);
        } catch (Exception e) {
            logger.error("获取业务评论项目异常：{}",e);
            return APIResponse.returnFail("系统异常！");
        }

    }

    @Override
    public APIResponse<List<RespCommentDetailScore>> getCommentDetailScore(Integer commentId) {
        logger.info("开始获取业务评论：{}的子项目打分：",commentId);
        if(commentId == null)
            return APIResponse.returnFail("commentId,不能为空");
        List<RespCommentDetailScore>  respCommentDetailScores = null;
        try {
            respCommentDetailScores = tbCommentDetailScoreMapper.findByCommentId(commentId);
            logger.info("end respCommentDetailScores:{}",respCommentDetailScores.toString());
            return APIResponse.returnSuccess(respCommentDetailScores);
        } catch (Exception e) {
            logger.error("获取评论项目分数失败：",e);
            return  APIResponse.returnFail("系统异常！");
        }
    }



    @Override
    public APIResponse<List<RespCommentDetailScore>> getRespCommentDetailScoreSum(ReqCommentQuery reqCommentQuery){
        try {
            if(!StringUtils.isNotBlank(reqCommentQuery.getSystemCode()))
                return APIResponse.returnFail("systemCode 不能为空");

            if(!StringUtils.isNotBlank(reqCommentQuery.getBusinessCode()))
                return APIResponse.returnFail("businessCode 不能为空");

            if( reqCommentQuery.getCommonParam() == null)
                return APIResponse.returnFail("commonParam 不能为空");

            logger.info("query comment pro sum score start ===>>{}",reqCommentQuery.toString());
            /****==============查询改业务所有评论==============*****/
            TbCommentExample tbCommentExample = new TbCommentExample();
            TbCommentExample.Criteria criteria = tbCommentExample.createCriteria();
            criteria.andSystemCodeEqualTo(reqCommentQuery.getSystemCode());
            criteria.andBusinessCodeEqualTo(reqCommentQuery.getBusinessCode());
            criteria.andCommonParamEqualTo(reqCommentQuery.getCommonParam());
            criteria.andCommentStatusEqualTo(Constants.IS_DELETE_TRUE);
            List<TbComment> lstTbComment = tbCommentMapper.selectByExample(tbCommentExample);

            /****==============查询所有评分==============*****/
            if (lstTbComment != null && lstTbComment.size() > 0){
                List<Integer> lstCommentId = new ArrayList<>();
                lstCommentId.addAll(this.coverListByPropertyIdTbComment(lstTbComment));
                if (lstCommentId.size() > 0){
                   List<RespCommentDetailScore> lstRespScore =  commentDetailScoreSumMapper.findCommentDetailSum(lstCommentId);
                   for (RespCommentDetailScore rs : lstRespScore ){
                       Double avgScore =  rs.getSumScore() / rs.getCount() ;
                       rs.setAvgScore(avgScore);
                   }
                    logger.info("query comment pro sum score end ===>>{}",lstRespScore.toString());
                   return APIResponse.returnSuccess(lstRespScore);
                }
            }
            return APIResponse.returnFail("系统异常");
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyIdTbComment(List<TbComment> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<TbComment, Integer>() {
                    @Override
                    public Integer apply(TbComment input) {
                        return input.getId();
                    }
                }
        ));
    }



}
